package com.chinaoryx.dwr;

import java.io.IOException;
import java.io.Writer;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.apache.log4j.Logger;

import org.apache.ibatis.session.ResultContext;
import org.apache.ibatis.session.ResultHandler;

public class CommonResultHandler implements ResultHandler {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger
			.getLogger(CommonResultHandler.class);

	private Writer out;

	boolean titleIsOk = false;

	public CommonResultHandler(Writer out) {
		super();
		this.out = out;
	}

	public void handleResult(ResultContext resultContext) {
		Object resultObj = resultContext.getResultObject();
		Map map = (Map) resultObj;
		int size = map.size();
		try {
			Set<Entry> set = map.entrySet();
			if (!titleIsOk) {
				out.write("<tr>");
				for (Entry entry : set) {
					out.write("<td>");
					out.write(entry.getKey().toString());
					out.write("</td>");
				}
				out.write("</tr>");
				this.titleIsOk = true;
			}

			out.write("<tr>");
			for (Entry entry : set) {
				out.write("<td>");
				out.write(entry.getValue().toString());
				out.write("</td>");
			}
			out.write("</tr>");

		} catch (IOException e) {
			throw new RuntimeException(e);
		}
		logger.info(resultObj);
	}

}
